package vip.xumy.core.golbal;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.log4j.Log4j2;
import vip.xumy.core.exception.CoreException;
import vip.xumy.core.pojo.com.Cache;
import vip.xumy.core.utils.DateUtil;
import vip.xumy.core.utils.StringUtil;

/**	All rights reserved
 *	author:mengyxu
 *	date:2019年9月19日
 */

@Log4j2
@EnableScheduling
@Component
public class GlobalBuffer {
	private static final Map<String, Cache> CACHES_MAP = new HashMap<>();
	private static int KEY_PREFIX_SEQ = 0;
	
	@Scheduled(cron = "${quartz.cron.clean.global:0 */10 * * * ?}")
	public void job() {
		log.info("清理已过期失效的缓存");
		GlobalBuffer.cleanCache();
	}

	
	public static Map<String, Cache> getBuffer(){
		return CACHES_MAP;
	}
	
	public static synchronized String getSeq() {
		return StringUtil.lpad(KEY_PREFIX_SEQ++ + "", "0", 10);
	}
	
	public static void addCache(String key,Cache cache) {
		CACHES_MAP.put(key, cache);
	}
	
	public static Cache getCache(String key) {
		Cache cache = CACHES_MAP.get(key);
		if(Cache.isEmpty(cache)) {
			CACHES_MAP.remove(key);
			return null;
		}
		return cache;
	}
	
	public static void removeCache(String key) {
		CACHES_MAP.remove(key);
	}
	
	public static synchronized void cleanCache() {
		Iterator<Entry<String, Cache>> iter = CACHES_MAP.entrySet().iterator();
		 while (iter.hasNext()){
			 Cache cache = iter.next().getValue();
			 if(cache == null || cache.getValue() == null) {
				 iter.remove();
		 	}
		 }
	}

	public static void setLoseTime(String key, String loseTime) throws CoreException {
		Long time = DateUtil.parse(loseTime, DateUtil.FORMAT19_LINE_YYYYMMDDHHMMSS).getTime();
		Cache.setLoseTime(getCache(key), time);
	}

}
